package edu.utexas.ipc;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

class Connector {

	static final int CONNECT_TIMEOUT = 5000;
	
	ServerSocket listener;
	ConnectHandler connectHandler;
	
	Connector(ConnectHandler ch) {
		this.listener = null;
		this.connectHandler = ch;
	}
	
	public void connect(InetSocketAddress localAddress, List<InetSocketAddress> serverList) throws IOException {
		
		listener = new ServerSocket(localAddress.getPort());
		
		// start a thread to process incoming connection requests.
		new Thread() {
			public void run() {
				try {
					while(true){
						Socket sckt = listener.accept();
						connectHandler.processConnection(sckt);
					}
				} catch (IOException e) {
					System.out.println("[" + listener.getLocalSocketAddress() + "] listener stopped.");
					// e.printStackTrace();
				}
			}
        }.start();
        
        // connect to other servers
        connectToServers(localAddress, serverList);
	}
	
	private void connectToServers(InetSocketAddress localAddress, List<InetSocketAddress> serverList) {

		for (InetSocketAddress server : serverList) {
			
			if (server.equals(localAddress)) {
				continue;
			}
			
			try {
				Socket sckt = new Socket();
				sckt.connect(server, CONNECT_TIMEOUT);
				connectHandler.processConnection(sckt);
				
			} catch (IOException e) {
				System.out.println("[" + localAddress + "] Failed connection to server at " + server);
			}
		}
	}
	
	void close() {
		try {
			listener.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
